/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 *
 * @author Brandon
 * @author Herman (2e Thread voor de reader)
 */
public class CpuComm implements Runnable {
    private Socket client;
    private BufferedWriter out;
    private BufferedReader in;
    private Thread t;
    private Parser parser = new Parser();
    public static boolean connected = false;
    
    public final ConcurrentLinkedQueue<HashMap<String, String[]>> queue;
    
    public CpuComm() {
        queue = new ConcurrentLinkedQueue<HashMap<String, String[]>>();
        t = new Thread(this);
    }
    
    public boolean connect(String ip, int port) {
        try {
            if(!connected){
                client = new Socket(ip, port);
                out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
                in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                t.start();
                connected = true;
            }
        } catch (IOException ex) {
            return false;
        }
        return true;
    }
    
    public void send(String command) {
        try {
            out.write(command);
            out.newLine();
            out.flush();
        } catch (IOException e) {
        }
    }
    
    public void close() {
        try {
            connected = false;
            out.flush();
            out.close();
        } catch (IOException e) {
        }
    }

    public void run() {
        String line;
        Thread cpufunctions = new Thread(new CpuFunctions(),"functions");
        cpufunctions.start();
        try {
            while ((line = in.readLine()) != null) {
            	
                HashMap<String, String[]> command = parser.parse(line);
                if(command != null) {
                    queue.add(command);
                    synchronized (queue) {
                        queue.notify();
                    }
                }
            }
            close();
        } catch (IOException e) {
        }
    }
}
